﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;
using TSL_Tools.SqlTools;
using ReportingEngine;
using System.IO;
using System.Windows.Forms.DataVisualization.Charting;
using System.Xml;
using System.ComponentModel;

namespace VSLT_Reporting
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region -- Charting Properties -------------------------------------------------
        List<ReportingEngine.TSL_ChartingDataSeries> chartObjects;
        List<System.Drawing.Color> plotColors = new List<System.Drawing.Color>();
        List<int> listOfSeriesToGroup = new List<int>();
        int currentPlotColor = 0;
        public int SegmentIntervalWidth = 1;
        #endregion

        #region -- Chart Template Methods -----------------------------------------
        private void LoadChartTemplate(ref Chart chart1, string fileName)
        {
            ChartSerializer _serializer = chart1.Serializer;
            _serializer.Load(fileName);
        }

        private void SaveChartTemplate(ref Chart chart1, string fileName)
        {
            SaveChartTemplate(ref chart1, fileName, true);
        }

        private void SaveChartTemplate(ref Chart chart1, string fileName, bool saveSettingsOnly)
        {
            ChartSerializer _serializer = chart1.Serializer;
            _serializer.IsTemplateMode = false;

            if (saveSettingsOnly)
                _serializer.Content = SerializationContents.Appearance;

            _serializer.Format = System.Windows.Forms.DataVisualization.Charting.SerializationFormat.Xml;
            _serializer.Save(fileName);
            tsslMessage.Content = String.Format(Msg_CHARTTEMPLATESAVED, fileName);
            return;

        }

        private void CopyChartToClipboard()
        {
            Chart chart = this.FindName("MyWinformChart") as Chart;

            using (MemoryStream ms = new MemoryStream())
            {
                chart.SaveImage(ms, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png);
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.StreamSource = ms;
                bi.EndInit();
                Clipboard.SetImage(bi);
                tsslMessage.Content = Msg_TSSL_CHARTCOPIEDTOCLIPBOARD;
            }
        }
        #endregion

        private TimeSpan BuildChartsForTesting()
        {
            DateTime dt = DateTime.Now;

            listOfSeriesToGroup.Clear();
            int x = 0;
            string currentChartSetName = chartObjects[x].name;
            string chartTitle = currentChartSetName;

            do
            {
                if (currentChartSetName == chartObjects[x].name)
                {
                    listOfSeriesToGroup.Add(x);
                }
                else //Found the first item of the next grouping. Process the previous group and reset to build the next group
                {
                    chartTitle = currentChartSetName;

                    BuildNewChartWithoutLegend(listOfSeriesToGroup, chartTitle, false);
                    currentChartSetName = chartObjects[x].name;
                    listOfSeriesToGroup.Clear();
                    listOfSeriesToGroup.Add(x);
                }
                x++;
            }
            while (x < chartObjects.Count);

            chartTitle = currentChartSetName;
            BuildNewChartWithoutLegend(listOfSeriesToGroup, chartTitle, false);

            return (TimeSpan)(DateTime.Now - dt);
        }

        public void AddHistogramChartSeries(ref Chart chart1, string sConn, TSL_ChartingDataSeries obj)
        {
            try
            {

                string _conn = sConn;
                string _cmd = String.Format(TSL_ReportingEngine.Sql_GETPERFMONCOUNTERSERIES, obj.runId, obj.instanceId);

                using (SqlConnection conn = new SqlConnection(_conn))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand(_cmd, conn))
                    {
                        SqlDataReader rdr = cmd.ExecuteReader();
                        DataTable _table = new DataTable();
                        chart1.DataBindTable(rdr, "Test Time");
                    }
                }
                int x = chart1.Series.Count - 1;
                chart1.Series[x].ChartType = SeriesChartType.Bar;
                chart1.Series[x].Name = obj.runId + "_" + obj.name;
                chart1.Series[x].Color = obj.lineColor;
                // HistogramChartHelper is a helper class found in the samples Utilities folder. 
                HistogramChartHelper histogramHelper = new HistogramChartHelper();

                // Show the percent frequency on the right Y axis.
                histogramHelper.ShowPercentOnSecondaryYAxis = false;

                // Specify number of segment intervals
                //histogramHelper.SegmentIntervalNumber = SegmentNumberInterval;

                // Or you can specify the exact length of the interval
                histogramHelper.SegmentIntervalWidth = SegmentIntervalWidth;


                // Create histogram series    
                histogramHelper.CreateHistogram(chart1, chart1.Series[x].Name, obj.name);
            }
            catch (Exception ex)
            {
                // Yeah I know. It should have code. When I get time, I'll add some.
            }
            finally
            {
            }
        }

        public void AddBoxPlotSeries(ref Chart chart1, string sConn, TSL_ChartingDataSeries obj)
        {
            string _conn = sConn;
            string _cmd = String.Format(TSL_ReportingEngine.Sql_GETPERFMONCOUNTERSERIES, obj.runId, obj.instanceId);

            using (SqlConnection conn = new SqlConnection(_conn))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(_cmd, conn))
                {
                    SqlDataReader rdr = cmd.ExecuteReader();
                    DataTable _table = new DataTable();
                    chart1.DataBindTable(rdr, "Test Time");
                }
            }
            int x = chart1.Series.Count - 1;

            // Set Box Plot chart type
            chart1.Series[x].ChartType = SeriesChartType.BoxPlot;

            // Specify data series name for the Box Plot
            chart1.Series[x]["BoxPlotSeries"] = chart1.Series[x].Name;

            // Set whiskers percentile
            chart1.Series[x]["BoxPlotWhiskerPercentile"] = "5";

            // Set box percentile
            chart1.Series[x]["BoxPlotPercentile"] = "30";

            // Hide Average line
            chart1.Series[x]["BoxPlotShowAverage"] = "true";

            // Show/Hide Median line
            chart1.Series[x]["BoxPlotShowMedian"] = "true";

            // Show Unusual points
            chart1.Series[x]["BoxPlotShowUnusualValues"] = "true";
        }
    }
}



